package vsm.vsm_server.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    // @Value("${spring.redis.host}")
    // private String host;

    // @Value("${spring.redis.port}")
    //  private int port;

    // 如果Redis有密码，则需要添加以下字段
    // @Value("${spring.redis.password}")
    // private String password;

    //如果导入了spring-boot-starter-data-redis，则不需要这一步，因为starter中已经自动配置了
    // @Bean


    /**
     配置redis序列化，按实际情况添加
     **/
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        /* 使用Json序列化，默认是JDK序列化 */
        // Key 使用字符串序列化
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);          // 普通 Key
        template.setHashKeySerializer(stringSerializer);     // Hash Key

        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        template.setDefaultSerializer(serializer);
        return template;
    }
}
